package com.wjv.example.springboot.base.exception;

import com.wjv.example.common.ResultInfo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.validation.BindException;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.MissingServletRequestParameterException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import org.springframework.web.servlet.NoHandlerFoundException;

import java.sql.SQLException;

/**
 * 统一异常处理
 */
@Slf4j
@RestControllerAdvice
public class DefaultExceptionAdvice {


    /**
     * 方法未发现异常处理。404
     *
     * @param e
     * @return
     */
    @ExceptionHandler(value = NoHandlerFoundException.class)
    public ResultInfo handleNoHandlerFoundException(NoHandlerFoundException e) {
        log.error("错误: {}", e.getLocalizedMessage());
        return ResultInfo.fail("404");
    }

    /**
     * 捕获请求参数缺失、参数规则验证失败异常
     *
     * @param e
     * @return
     */
    @ExceptionHandler(value = {
            MissingServletRequestParameterException.class,
            BindException.class,
            MethodArgumentNotValidException.class})
    public ResultInfo handleConstraintViolationException(Exception e) {
        log.error("参数验证失败: ", e);
        String mess = e.getLocalizedMessage();
        BindingResult bindingResult = null;
        if (e instanceof BindException) {
            bindingResult = (BindingResult) e;
        }
        if (e instanceof MethodArgumentNotValidException) {
            bindingResult = ((MethodArgumentNotValidException) e).getBindingResult();
        }
        if (null != bindingResult) {
            mess = bindingResult.getFieldError().getField() + ":" + bindingResult.getFieldError().getDefaultMessage();
        }

        return ResultInfo.fail(mess);
    }

    /**
     * SQLException sql异常处理
     */
    @ExceptionHandler({SQLException.class})
    public ResultInfo handleSQLException(SQLException e) {
        return ResultInfo.fail("服务运行SQLException异常");
    }

    /**
     * 其他异常
     *
     * @return
     */
    @ExceptionHandler(value = Exception.class)
    public ResultInfo handleException(Exception e) {
        log.error("异常: ", e);
        return ResultInfo.fail("系统错误");
    }

}
